package com.mybatisPlus.servie;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mybatisPlus.Utils.JwtUtils;
import com.mybatisPlus.common.Result;
import com.mybatisPlus.dao.entity.MyFile;
import com.mybatisPlus.dao.entity.User;
import com.mybatisPlus.dao.mapper.FileMapper;
import com.mybatisPlus.dao.service.IFileService;
import com.mybatisPlus.dao.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;
/**
 * 处理文件上传下载
 * @author liHeWei
 * @since 2022-04-16
 */
@Service
public class FileService {

    @Value("${imgFile}")
    private String dirPath;  //图片上传保存地址

    @Autowired
    private IUserService userService;
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private IFileService fileService;

    //获取文件列表
    public Result getFileList(int current,HttpServletRequest request){
        String username = JwtUtils.getString(request.getHeader("Token"), "username");
        Long userId=userService.getOne(new QueryWrapper<User>().eq("username", username)).getId();
        Page<MyFile> page=new Page<>(current,5);
        return Result.succ(fileMapper.selectPage(page,new QueryWrapper<MyFile>().eq("user_id", userId)));
    }

    //上传文件
    public Result uploadFile(MultipartFile file, HttpServletRequest request){
        //获取用户名
        String username = JwtUtils.getString(request.getHeader("Token"), "username");
        String fileName=file.getOriginalFilename();
        Long userId=userService.getOne(new QueryWrapper<User>().eq("username", username)).getId();
        MyFile myFile=new MyFile();
        //生成唯一文件名
        String newFileName= UUID.randomUUID()+"-"+fileName;
        myFile.setFileName(newFileName);
        myFile.setUserId(userId);
        File filePath=new File(dirPath);
        if(!filePath.exists()){
            if(!filePath.mkdirs()) return Result.fail("无法生成文件路径");
        }
        try{
            //移入文件至目标目录
            file.transferTo(new File(dirPath,newFileName));
            fileService.save(myFile);
            return Result.succ(newFileName);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("未知错误。请联系管理员");
        }
    }

    //下载文件
    public void downloadFile(String name,HttpServletResponse response){
        try {
            // path是指想要下载的文件的路径
            File file = new File(dirPath+name);
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    //删除文件
    public Result delFile(String name){
        File file=new File(dirPath+name);
        //效验文件是否存在
        if(file.exists()){
            if(file.delete()) {
                fileService.remove(new QueryWrapper<MyFile>().eq("fileName", name));
                return Result.succ(null);
            }
            else return Result.fail("删除失败,请联系管理员");
        }else return Result.fail("文件不存在，删除失败");
    }
}
